<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>WebSocket Test</title>
  <script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
</head>

<body>
  <h1>WebSocket Test</h1>
  <button id="connectButton">Connect WebSocket</button>
  <p id="status">Status: Not Connected</p>

  <script>
    // 获取DOM元素
    const statusElement = document.getElementById('status');
    const connectButton = document.getElementById('connectButton');

    // 定义WebSocket连接
    let socket;

    // 点击按钮连接 WebSocket
    connectButton.addEventListener('click', () => {
      if (socket) {
        socket.close();  // 如果已连接，先关闭之前的连接
      }

      // 连接到 WebSocket
      socket = io('wss://139.196.234.35', {  // 使用外部已声明的 socket 变量
        path: '/socket.io',
        autoConnect: false,
        transports: ['websocket'],
      });

      socket.on('connect', () => {
        statusElement.innerText = 'Status: Connected';
        console.log('WebSocket connected');
      });

      socket.on('connect_error', (err) => {
        statusElement.innerText = 'Status: Connection Failed';
        console.error('WebSocket connection error:', err);
      });

      socket.on('disconnect', () => {
        statusElement.innerText = 'Status: Disconnected';
        console.log('WebSocket disconnected');
      });

      socket.connect(); // 需要显式调用 connect() 来建立连接
    });
  </script>
</body>

</html>
